<template>
  <div class="container-wrapper">
    <div class="header-wrapper">
      <div class="header-left">
        <el-button type="primary" @click="handleOpenDialog()">上传文件</el-button>
      </div>
      <div class="header-right">
        <el-button :icon="Refresh" circle @click="listFile" />
      </div>
    </div>
    <div class="main-wrapper">
      <el-table :data="paginatedFileList" border height="100%" class="table">
        <el-table-column prop="Key" label="文件名称" align="center"></el-table-column>
        <el-table-column prop="LastModified" label="更新时间" width="250" align="center">
          <template #default="scope">
            {{ new Date(scope.row.LastModified).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="Size" label="文件大小" width="250" align="center">
          <template #default="scope">
            {{ (scope.row.Size / 1024).toFixed(2) }} KB
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button @click="deleteFile(scope.row)" type="danger" link>删除</el-button>
            <el-button @click="downloadFile(scope.row)" type="primary" link>下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          class="pagination"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="fileList.length"
          @current-change="handlePageChange"
          layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>

    <!-- 弹框 -->
    <el-dialog
        v-model="dialogVisible"
        title="文件上传"
        width="750px">
      <el-upload
          class="upload-demo"
          drag
          action="#"
          :show-file-list="false"
          :http-request="handleUploadFile">
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">
          拖动文件到这里或<em>点击上传</em>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog()">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue';
import COS from 'cos-js-sdk-v5'; // 引入腾讯COS SDK
import {COS_CONFIG} from '@/config';
import {Refresh, UploadFilled} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";

const dialogVisible = ref(false);
const fileList = ref([]); // 文件列表
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示的文件数量

const cos = new COS({
  SecretId: COS_CONFIG.SecretId,
  SecretKey: COS_CONFIG.SecretKey,
});

// 计算分页后的文件列表
const paginatedFileList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return fileList.value.slice().sort((a, b) => new Date(b.LastModified) - new Date(a.LastModified)).slice(start, end);
});

// 上传文件
const uploadFile = (file) => {
  cos.putObject({
    Bucket: COS_CONFIG.Bucket,
    Region: COS_CONFIG.Region,
    Key: file.name,
    Body: file,
  }, (err, _data) => {
    if (err) {
      console.error(err);
    } else {
      ElMessage.success('文件上传成功')
      listFile();
    }
  });
};

// 删除文件
const deleteFile = (key) => {
  cos.deleteObject({
    Bucket: COS_CONFIG.Bucket,
    Region: COS_CONFIG.Region,
    Key: key.Key,
  }, (err, _data) => {
    if (err) {
      console.error(err);
    } else {
      ElMessage.success('文件删除成功')
      listFile();
    }
  });
};

// 获取文件列表
const listFile = () => {
  cos.getBucket({
    Bucket: COS_CONFIG.Bucket,
    Region: COS_CONFIG.Region,
  }, (err, data) => {
    if (err) {
      console.error(err);
    } else {
      // 过滤掉文件夹，只保留文件
      fileList.value = data.Contents.filter(item => item.Size > 0); // 只保留大小大于0的项
    }
  });
};

// 在组件挂载时获取文件列表
onMounted(() => {
  listFile();
});

// 处理文件选择
const handleUploadFile = (file) => {
  if (file.file) {
    uploadFile(file.file);
  }
}

// 打开弹框
const handleOpenDialog = () => {
  dialogVisible.value = true;
};

// 关闭弹框
const handleCloseDialog = () => {
  dialogVisible.value = false;
};

// 下载文件
const downloadFile = (file) => {
  const url = `https://${COS_CONFIG.Bucket}.cos.${COS_CONFIG.Region}.myqcloud.com/${file.Key}`; // 构建下载链接
  window.open(url); // 打开下载链接
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};
</script>

<style lang="scss" scoped>
@use "./index.scss";
</style>